/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package nl.maxato.xmlservices;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.JAXBContext;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import nl.maxato.domain.Athlete;
import nl.maxato.domain.Calendar;
import nl.maxato.domain.Calendar_Week;
import nl.maxato.domain.Club;
import nl.maxato.domain.Continent;
import nl.maxato.domain.Event;
import nl.maxato.domain.Nation;
import nl.maxato.domain.Regio;
import nl.maxato.domain.Sponsor;
import nl.maxato.domain.Week;
import nl.maxato.domain.WeeklyTest;
import nl.maxato.domain.World;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *
 * @author Fam Gloudemans
 */
public class ConvertXMLData {


    public ConvertXMLData() {
    }

    nl.maxato.domain.Club convertClubData() {
        try {

            File fXmlFile = new File("xml/team.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);
            doc.getDocumentElement().normalize();
            NodeList nList = doc.getElementsByTagName("maxi-xml");

            for (int temp = 0; temp < nList.getLength(); temp++) {

                Node nNode = nList.item(temp);
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                    Element eElement = (Element) nNode;
                    String teamId = getTagValue("teamId", eElement);
                    String teamName = getTagValue("teamName", eElement);
                    String owner = getTagValue("owner", eElement);
                    String founded = getTagValue("founded", eElement);
                    String arenaId = getTagValue("arenaId", eElement);
                    String leagueId = getTagValue("leagueId", eElement);
                    String nationId = getTagValue("nationId", eElement);
                    String regionId = getTagValue("regionId", eElement);
                    nl.maxato.domain.Club club = new Club(teamId, teamName, owner, founded, arenaId, leagueId, nationId, regionId);
                    return club;
                }
            }
        } catch (Exception e) {

            return null;
        }
        return null;
    }

    File getLastFileOfTheMap(String dir) {

        File fl = new File(dir);
        File[] files = fl.listFiles(new FileFilter() {

            public boolean accept(File file) {
                return file.isFile();
            }
        });
        long lastMod = Long.MIN_VALUE;
        File choise = null;
        for (File file : files) {
            if (file.lastModified() > lastMod) {
                choise = file;
                lastMod = file.lastModified();
            }
        }
        //System.out.println("Filename, van de laatste die is opgehaald: " + choise.getName());
        return choise;
    }

    List<Athlete> xmlToAthletes() {
        List<Athlete> listAtleet = new ArrayList<Athlete>();
        System.out.println("Atleten omzetten, hopelijk komt dit 1x voor in de log?");
        try {

            File fXmlFile = getLastFileOfTheMap("xml/athletes/");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);
            doc.getDocumentElement().normalize();
            System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
            NodeList nList = doc.getElementsByTagName("athlete");
            System.out.println("-----------------------");
            for (int temp = 0; temp < nList.getLength(); temp++) {
                Node nNode = nList.item(temp);
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) nNode;
//                    System.out.println("athleteId : " + getTagValue("athleteId", eElement));
//                    System.out.println("name : " + getTagValue("name", eElement));
//                    System.out.println("surname : " + getTagValue("surname", eElement));
//                    System.out.println("age : " + getTagValue("age", eElement));
                    int athleteId = Integer.parseInt(getTagValue("athleteId", eElement));
                    String name = (getTagValue("name", eElement));
                    String surname = (getTagValue("surname", eElement));
                    int sex = Integer.parseInt(getTagValue("sex", eElement));
                    int age = Integer.parseInt(getTagValue("age", eElement));
                    int nationId = Integer.parseInt(getTagValue("nationId", eElement));
                    int owner = Integer.parseInt(getTagValue("owner", eElement));
                    int wage = Integer.parseInt(getTagValue("wage", eElement));
                    int height = Integer.parseInt(getTagValue("height", eElement));
                    int weight = Integer.parseInt(getTagValue("weight", eElement));
                    int fans = Integer.parseInt(getTagValue("fans", eElement));
                    Sponsor sponsor = null;
                    int maxid = Integer.parseInt(getTagValue("maxid", eElement));
                    int form = Integer.parseInt(getTagValue("form", eElement));
                    int care = Integer.parseInt(getTagValue("care", eElement));
                    int experience = Integer.parseInt(getTagValue("experience", eElement));
                    int mood = Integer.parseInt(getTagValue("mood", eElement));
                    int specialtyId = Integer.parseInt(getTagValue("specialtyId", eElement));
                    int favoriteEventId = Integer.parseInt(getTagValue("favoriteEventId", eElement));
                    int strenght = Integer.parseInt(getTagValue("strenght", eElement));
                    int stamina = Integer.parseInt(getTagValue("stamina", eElement));
                    int speed = Integer.parseInt(getTagValue("speed", eElement));
                    int agility = Integer.parseInt(getTagValue("agility", eElement));
                    int jump = Integer.parseInt(getTagValue("jump", eElement));
                    int throwing = Integer.parseInt(getTagValue("throw", eElement));
                    int specialty1 = Integer.parseInt(getTagValue("specialty1", eElement));
                    int specialty2 = Integer.parseInt(getTagValue("specialty2", eElement));
                    int coachId = Integer.parseInt(getTagValue("coachId", eElement));
                    int injury = Integer.parseInt(getTagValue("injury", eElement));
                    String sell = getTagValue("sell", eElement);
                    int youth = Integer.parseInt(getTagValue("youth", eElement));
                    int specialtyIdTrained = Integer.parseInt(getTagValue("specialtyIdTrained", eElement));
                    Athlete atleet = new Athlete(athleteId, name, surname, sex, age, nationId, owner, wage, height, weight, fans, sponsor, maxid, form, care, experience, mood, specialtyId, favoriteEventId, strenght, stamina, speed, agility, jump, throwing, specialty1, specialty2, coachId, injury, sell, youth, specialtyIdTrained);
                    listAtleet.add(atleet);
                }
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            System.out.println("--------------");
            System.out.println(e.toString());
            return null;
        }
        return listAtleet;
    }

    List<Athlete> zetAtleetDataOmDoorDatum(String datum) {
        List<Athlete> listAtleet = new ArrayList<Athlete>();
        try {

            //File fXmlFile = getLastFileOfTheMap("xml/athletes/");
            File fXmlFile = new File("xml/athletes/" + datum + ".xml");
            //
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);
            doc.getDocumentElement().normalize();
            NodeList nList = doc.getElementsByTagName("athlete");
            for (int temp = 0; temp < nList.getLength(); temp++) {
                Node nNode = nList.item(temp);
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) nNode;
                    int athleteId = Integer.parseInt(getTagValue("athleteId", eElement));
                    String name = (getTagValue("name", eElement));
                    String surname = (getTagValue("surname", eElement));
                    int sex = Integer.parseInt(getTagValue("sex", eElement));
                    int age = Integer.parseInt(getTagValue("age", eElement));
                    int nationId = Integer.parseInt(getTagValue("nationId", eElement));
                    int owner = Integer.parseInt(getTagValue("owner", eElement));
                    int wage = Integer.parseInt(getTagValue("wage", eElement));
                    int height = Integer.parseInt(getTagValue("height", eElement));
                    int weight = Integer.parseInt(getTagValue("weight", eElement));
                    int fans = Integer.parseInt(getTagValue("fans", eElement));
                    Sponsor sponsor = null;
                    int maxid = Integer.parseInt(getTagValue("maxid", eElement));
                    int form = Integer.parseInt(getTagValue("form", eElement));
                    int care = Integer.parseInt(getTagValue("care", eElement));
                    int experience = Integer.parseInt(getTagValue("experience", eElement));
                    int mood = Integer.parseInt(getTagValue("mood", eElement));
                    int specialtyId = Integer.parseInt(getTagValue("specialtyId", eElement));
                    int favoriteEventId = Integer.parseInt(getTagValue("favoriteEventId", eElement));
                    int strenght = Integer.parseInt(getTagValue("strenght", eElement));
                    int stamina = Integer.parseInt(getTagValue("stamina", eElement));
                    int speed = Integer.parseInt(getTagValue("speed", eElement));
                    int agility = Integer.parseInt(getTagValue("agility", eElement));
                    int jump = Integer.parseInt(getTagValue("jump", eElement));
                    int throwing = Integer.parseInt(getTagValue("throw", eElement));
                    int specialty1 = Integer.parseInt(getTagValue("specialty1", eElement));
                    int specialty2 = Integer.parseInt(getTagValue("specialty2", eElement));
                    int coachId = Integer.parseInt(getTagValue("coachId", eElement));
                    int injury = Integer.parseInt(getTagValue("injury", eElement));
                    String sell = getTagValue("sell", eElement);
                    int youth = Integer.parseInt(getTagValue("youth", eElement));
                    int specialtyIdTrained = Integer.parseInt(getTagValue("specialtyIdTrained", eElement));
                    Athlete atleet = new Athlete(athleteId, name, surname, sex, age, nationId, owner, wage, height, weight, fans, sponsor, maxid, form, care, experience, mood, specialtyId, favoriteEventId, strenght, stamina, speed, agility, jump, throwing, specialty1, specialty2, coachId, injury, sell, youth, specialtyIdTrained);
                    listAtleet.add(atleet);
                }
            }
        } catch (Exception e) {

            return null;
        }
        return listAtleet;
    }

    private String getTagValue(String sTag, Element eElement) {
        NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
        Node nValue = (Node) nlList.item(0);
        return nValue.getNodeValue();

    }

    World worldDataOmzetten() {
        List<nl.maxato.domain.Continent> continenten = new ArrayList<nl.maxato.domain.Continent>();
        List<Regio> regios = new ArrayList<Regio>();
        List<Nation> landen = new ArrayList<Nation>();
        Continent continent = new Continent();
        Nation nation = new Nation();
        try {

            JAXBContext ctx = JAXBContext.newInstance(World.class);
            File xmlfile = new File("xml/world.xml");
            World world = (World) ctx.createUnmarshaller().unmarshal(xmlfile);
            for (nl.maxato.domain.Continent c : world.getContinent()) {
                for (Nation n : c.getNationsList()) {
                    for (Regio r : n.getRegiosList()) {
                        Regio regio = new Regio(r.getIdRegio(), r.getNameRegio());
                        regios.add(regio);
                    }
                    nation = new Nation(regios, n.getIdNation(), n.getNameNation());
                    landen.add(nation);
                }
                continent = new Continent(landen, c.getIdContinent(), c.getNameContinent());
                continenten.add(continent);
            }
        } catch (Exception ex) {
            Logger.getLogger(ConvertXMLData.class.getName()).log(Level.SEVERE, null, ex);
        }
        return new World(continenten);
    }

    WeeklyTest weeklyTestDataOmzetten() {
        List<Event> events = new ArrayList<Event>();
        List<Week> weeks = new ArrayList<Week>();
        Event event = new Event();
        Athlete athlete = new Athlete();
        ArrayList<Athlete> ats = new ArrayList<Athlete>();
        try {

            JAXBContext ctx = JAXBContext.newInstance(WeeklyTest.class);
            File xmlfile = new File("xml/weeklytest.xml");
            WeeklyTest wt = (WeeklyTest) ctx.createUnmarshaller().unmarshal(xmlfile);
            for (Athlete a : wt.getAthletesArrayList()) {
                events = new ArrayList<Event>();
                for (Event e : a.getEventsArrayList()) {
                    weeks = new ArrayList<Week>();
                    for (Week w : e.getWeeksEvent()) {
                        weeks.add(w);
                    }
                    event = new Event(e.getIdEvent(), weeks);
                    events.add(event);
                }
                athlete = new Athlete(a.getIdOfAthlete(), events);
                ats.add(athlete);
            }


        } catch (Exception ex) {
            Logger.getLogger(ConvertXMLData.class.getName()).log(Level.SEVERE, null, ex);
        }
        return new WeeklyTest(ats);
    }

    Calendar convertCalendarData() {
        List<Calendar_Week> weken = new ArrayList<Calendar_Week>();
        ArrayList<Integer> competities = new ArrayList<Integer>();
        int season = 0;
        int currentWeek = 0;
        try {
            JAXBContext jct = JAXBContext.newInstance(Calendar.class);
            File xmlfile = new File("xml/calendar.xml");
            Calendar calendar = (Calendar) jct.createUnmarshaller().unmarshal(xmlfile);
            season = calendar.getSeasonCalendar();
            currentWeek = calendar.getCurrentWeekCalendar();
            System.out.println(season + " SEASON " + currentWeek);
            for (nl.maxato.domain.Calendar_Week c : calendar.getWeeksCalendar()) {
                for (Integer co : c.getCompetitionCalendarWeek()) {
                    competities.add(co);
                }
                Calendar_Week cw = new Calendar_Week(c.getDayCalendarWeek(), c.getMonthCalendarWeek(), c.getYearCalendarWeek(), competities);
                weken.add(cw);
                competities = new ArrayList<Integer>();
            }
        } catch (Exception ex) {
            Logger.getLogger(ConvertXMLData.class.getName()).log(Level.SEVERE, null, ex);
        }
        return new Calendar(season, currentWeek, weken);
    }
}
